<template>
  <div class="app-container">
    <!-- 顶部导航 -->
    <div class="top-navbar">
      <!-- <div class="nav-tabs"> -->
      <!-- <el-radio-group v-model="activeTab" size="medium"> -->
      <!-- <el-radio-button label="类别"></el-radio-button> -->
      <!-- <el-radio-button label="客户"></el-radio-button> -->
      <!-- <el-radio-button label="供应商" class="active"></el-radio-button> -->
      <!-- <el-radio-button label="商品"></el-radio-button> -->
      <!-- <el-radio-button label="支出"></el-radio-button>
          <el-radio-button label="收入"></el-radio-button> -->
      <!-- </el-radio-group> -->
      <!-- </div> -->

      <div class="search-area">
        <el-input
          v-model="listQuery.name"
          placeholder="请输入类别名称"
          clearable
          style="width: 200px"
        />

        <!-- <el-select
          v-model="listQuery.status"
          placeholder="显示启用类别"
          style="width: 150px; margin-left: 10px"
        >
          <el-option label="显示启用类别" value="enabled"></el-option>
          <el-option label="显示禁用类别" value="disabled"></el-option>
          <el-option label="显示全部类别" value="all"></el-option>
        </el-select> -->

        <el-button
          type="primary"
          class="search-btn"
          @click="handleFilter"
        >查询</el-button>
      </div>

      <div class="operation-buttons">
        <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <!-- <el-button @click="handleDisable">禁用</el-button>
        <el-button @click="handleEnable">启用</el-button>
        <el-button @click="handleRefresh">刷新</el-button> -->
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="supplierTypeList"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      header-cell-style="background-color: #f5f7fa; color: #333;"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->

      <el-table-column label="类别" prop="name" width="width" align="center" />

      <!-- <el-table-column label="状态" align="center" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column> -->

      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            <!-- <i class="el-icon-edit"></i> -->
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            <!-- <i class="el-icon-delete"></i> -->
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div v-if="total > 0" class="pagination-container">
      <el-pagination
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      :title="form.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form
        ref="categoryForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类别名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selSupplierTypeListApi,
  addSupplierTypeApi,
  updateSupplierTypeApi,
  deleteSupplierTypeApi
} from '@/api/system'
export default {
  name: 'VendorClass',
  data() {
    return {
      activeTab: '供应商',
      listLoading: false,
      list: [
        { id: 1, name: '广东', enabled: true },
        { id: 2, name: '├ 海鲜供应商', enabled: true },
        { id: 3, name: '├ 测试', enabled: true },
        { id: 4, name: '├ 高水饮料供应商', enabled: true },
        { id: 5, name: '├ 食品供应商', enabled: true },
        { id: 6, name: '湖南', enabled: true },
        { id: 7, name: '├ 零食供应商', enabled: true },
        { id: 8, name: '├ 辣条供应商', enabled: true }
      ],
      total: 8,
      supplierTypeList: [], // 供应商类别列表
      total: 0, // 供应商类别总数
      // 查询参数
      listQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        status: ''
      },
      multipleSelection: [],
      dialogFormVisible: false,
      dialogStatus: 'create',
      form: {
        id: undefined,
        name: '',
        enabled: true
      },
      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      tempRoute: {}
    }
  },
  created() {
    // this.getList();
    this.getSupplierTypeList()
  },
  methods: {
    // getList() {
    //   this.listLoading = true;
    //   // 这里应该是API调用，但现在使用模拟数据
    //   setTimeout(() => {
    //     let filteredList = [...this.list];

    //     // 根据关键字筛选
    //     if (this.listQuery.keyword) {
    //       const keyword = this.listQuery.keyword.toLowerCase();
    //       filteredList = filteredList.filter((item) =>
    //         item.name.toLowerCase().includes(keyword)
    //       );
    //     }

    //     // 根据状态筛选
    //     if (this.listQuery.status !== "all") {
    //       const enabled = this.listQuery.status === "enabled";
    //       filteredList = filteredList.filter(
    //         (item) => item.enabled === enabled
    //       );
    //     }

    //     this.list = filteredList;
    //     this.total = filteredList.length;
    //     this.listLoading = false;
    //   }, 500);
    // },

    // 获取供应商类别列表
    async getSupplierTypeList() {
      this.listLoading = true
      const res = await selSupplierTypeListApi(this.listQuery)
      this.supplierTypeList = res.records || []
      this.total = res.total || 0
      this.listLoading = false
    },
    handleFilter() {
      this.listQuery.page = 1
      // this.getList();
      this.getSupplierTypeList()
    },
    // 分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      // this.getList();
      this.getSupplierTypeList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      // this.getList();
      this.getSupplierTypeList()
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        enabled: true
      }
    },
    // 新增
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {
        name: ''
      }
    },
    // 编辑
    handleEdit(row) {
      this.dialogFormVisible = true
      this.form = {
        id: row.id,
        name: row.name
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.categoryForm.validate(async(valid) => {
        if (valid) {
          try {
            const params = {
              name: this.form.name
            }

            if (!this.form.id) {
              // 新增供应商类别
              const res = await addSupplierTypeApi(params)
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            } else {
              // 编辑供应商类别
              const res = await updateSupplierTypeApi({
                ...params,
                id: this.form.id
              })

              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            }
            this.dialogFormVisible = false
            this.getSupplierTypeList() // 刷新列表数据
          } catch (error) {
            console.error('操作失败:', error)
            this.$message({
              type: 'error',
              message: '操作失败: ' + (error.message || '未知错误')
            })
          }
        }
      })
    },
    handleStatusChange(row) {
      this.$message({
        message: `状态已${row.enabled ? '启用' : '禁用'}`,
        type: 'success'
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该供应商分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 模拟删除
          const res = await deleteSupplierTypeApi(row.id)
          if (res.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getSupplierTypeList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        })
    },
    handleDisable() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要禁用的分类',
          type: 'warning'
        })
        return
      }

      const selectedIds = this.multipleSelection.map((item) => item.id)

      this.list.forEach((item) => {
        if (selectedIds.includes(item.id)) {
          item.enabled = false
        }
      })

      this.$message({
        type: 'success',
        message: '禁用成功!'
      })
    },
    handleEnable() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择要启用的分类',
          type: 'warning'
        })
        return
      }

      const selectedIds = this.multipleSelection.map((item) => item.id)

      this.list.forEach((item) => {
        if (selectedIds.includes(item.id)) {
          item.enabled = true
        }
      })

      this.$message({
        type: 'success',
        message: '启用成功!'
      })
    },
    handleRefresh() {
      this.listQuery.keyword = ''
      this.listQuery.status = 'enabled'
      this.getList()
      this.$message({
        message: '刷新成功',
        type: 'success'
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.top-navbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20px;
}

.nav-tabs {
  display: flex;
  margin-right: 20px;
}

.nav-tabs .el-radio-button__inner {
  border-radius: 0;
}

.nav-tabs .active {
  background-color: #409eff;
  color: white;
}

.search-area {
  display: flex;
  align-items: center;
  flex-grow: 1;
}

.search-btn {
  margin: 0 15px;
}

.info-btn {
  margin-right: 20px;
  color: #409eff;
}

.operation-buttons {
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: center;
}
</style>
